package me.zhangyifeng.blog.web.controller.front;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.servlet.ServletUtil;
import me.zhangyifeng.blog.model.domain.Attachment;
import me.zhangyifeng.blog.model.domain.Log;
import me.zhangyifeng.blog.model.domain.User;
import me.zhangyifeng.blog.model.dto.JsonResult;
import me.zhangyifeng.blog.model.dto.LogConstant;
import me.zhangyifeng.blog.model.dto.MaydayConst;
import me.zhangyifeng.blog.service.AttachmentService;
import me.zhangyifeng.blog.service.LogService;
import me.zhangyifeng.blog.util.MaydayUtil;
import net.coobird.thumbnailator.Thumbnails;

/**
 * 用户文件上传控制器
 */
@Controller
@RequestMapping(value = "/user/file")
public class UserFileController {
    
    @Autowired
    private AttachmentService attachmentService;
    
    @Autowired
    private LogService logService;
    
    /**
     * 用户上传文件
     */
    @PostMapping(value = "/upload")
    @ResponseBody
    public JsonResult upload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
        // 验证用户是否登录
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(MaydayConst.USER_SESSION_KEY);
        if (user == null) {
            return new JsonResult(false, "请先登录");
        }
        
        if (file.isEmpty()) {
            return new JsonResult(false, "文件不能为空");
        }
        
        try {
            // 获取当前年月以创建目录
            Date date = new Date();
            String yearMonth = new SimpleDateFormat("yyyy/MM").format(date);
            
            // 获取上传文件名
            String fileName = file.getOriginalFilename();
            // 获取文件后缀
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            // 生成新的文件名
            String newFileName = generateFileName(fileName);
            
            // 判断文件是否为图片
            if (!MaydayUtil.isPicture(newFileName)) {
                return new JsonResult(false, "请选择图片格式的文件");
            }
            
            // 文件上传和缩略图生成
            String filePath = "/upload/" + yearMonth;
            // 创建文件目录
            File uploadPath = new File(System.getProperty("user.dir") + "/target/classes/static" + filePath);
            if (!uploadPath.exists()) {
                uploadPath.mkdirs();
            }
            
            // 转存文件
            file.transferTo(new File(uploadPath + "/" + newFileName));
            
            // 生成缩略图
            String thumbnailName = newFileName.substring(0, newFileName.lastIndexOf(".")) + "_small" + suffix;
            Thumbnails.of(new StringBuffer(uploadPath + "/" + newFileName).toString())
                    .size(256, 256)
                    .keepAspectRatio(false)
                    .toFile(uploadPath + "/" + thumbnailName);
            
            // 生成附件
            Attachment attachment = new Attachment();
            attachment.setPictureName(fileName);
            attachment.setPicturePath(filePath + "/" + newFileName);
            attachment.setPictureSmallPath(filePath + "/" + thumbnailName);
            attachment.setPictureSuffix(suffix);
            attachment.setPictureCreateDate(date);
            attachment.setPictureSize(MaydayUtil.parseSize(file.getSize()));
            attachment.setPictureType(file.getContentType());
            attachment.setPictureWh(MaydayUtil.getImageWh(new File(uploadPath + "/" + newFileName)));
            attachmentService.save(attachment);
            
            // 添加日志
            logService.save(new Log(LogConstant.UPLOAD_ATTACHMENT, LogConstant.UPLOAD_SUCCESS,
                    ServletUtil.getClientIP(request), new Date()));
            
            // 返回结果
            return new JsonResult(true, "上传成功", attachment);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "上传失败");
        }
    }
    
    /**
     * 生成文件名
     */
    private String generateFileName(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateName = format.format(new Date()) + RandomUtil.randomNumbers(7);
        return dateName + suffix;
    }
}
